#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
#include <QTime>
#include <QDataStream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
     ui->textBrowser->document()->setMaximumBlockCount(200);
     m_socket  = new QTcpSocket(this);
     connect(m_socket, SIGNAL(readyRead()), this, SLOT(slot_ReadData()));
     connect(m_socket, SIGNAL(connected()), this, SLOT(slot_socketConnected()));
     connect(m_socket, SIGNAL(disconnected()), this, SLOT(slot_socketDisconnected()));
     connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slot_socketError(QAbstractSocket::SocketError)));

}

Widget::~Widget()
{
    if(m_socket){
        m_socket->close();
    }
    delete m_socket;
    delete ui;
}


void Widget::on_m_btnce_clicked()
{
    int port = ui->Port->value();
    QString hostAddress = ui->lineEditPeerAddress->text();
    if (hostAddress.isEmpty())
        return;
    if(ui->m_btnce->text()=="连接")
    {
        if(m_socket){
            m_socket->close();
            m_socket->connectToHost(hostAddress,port);
            if(m_socket->isOpen()) ui->m_btnce->setText("断开");
        }

    }
    else if(ui->m_btnce->text()=="断开")
    {
        if(m_socket)
        {
             m_socket->close();
             ui->m_btnce->setText("连接");
        }
    }
}

void Widget::on_m_btnSend_clicked()
{
    if(!m_socket)
    {
       return;
    }

    QString text = ui->lineEdit_send->text();
       if (m_socket->isWritable() && !text.isEmpty())
       {
           QString msg = QString("%1 发送数据：%2").arg(QTime::currentTime().toString()). arg(text);
           ui->textBrowser->append(msg);
          QByteArray senddata = QByteArray::fromHex(text.toLatin1());
           m_socket->write(senddata);
       }

}

void Widget::slot_ReadData()
{
    if(!m_socket)
    {
       return;
    }

    if (m_socket->bytesAvailable() > 0)
        {
                QByteArray data = m_socket->readAll();
                QString hexStr;
               for (int i = 0; i < data.count(); i++){
                   hexStr.append(tr("%1 ").arg((quint8)data.at(i),2,16,QLatin1Char('0')).toUpper());
               }
                QString msg = QString("%1 收到数据：%2").arg(QTime::currentTime().toString()).arg(hexStr);
                ui->textBrowser->append(msg);
                slot_InterpretingData(data);
        }
}

void Widget::slot_socketConnected()
{
    QString msg = QString("%1 已连接 ").arg(QTime::currentTime().toString());
    ui->textBrowser->append(msg);
}

void Widget::slot_socketDisconnected()
{
    QString msg = QString("%1 已断开 ").arg(QTime::currentTime().toString());
    ui->textBrowser->append(msg);
}

void Widget::slot_socketError(QAbstractSocket::SocketError)
{
    QString msg = QString("%1 发生错误：%2").arg(QTime::currentTime().toString()).arg(m_socket->errorString());
    ui->textBrowser->append(msg);
}

void Widget::slot_InterpretingData(QByteArray &readdata)
{
    qDebug()<<" readdata.size:"<<readdata.size();
    if(readdata.count()<=0)return;
    if(readdata.count()<9)return;
     int nfun = readdata.at(7);
     int nlen = readdata.at(8);
      qDebug()<<" data.fun:"<<nfun;
      qDebug()<<" data.len:"<<nlen;
      QString strVal;
      QByteArray vals = readdata.mid(9,nlen);
    if(nfun==3)//模拟量
    {
        QDataStream dataStream(vals);
        dataStream.setByteOrder(QDataStream::BigEndian);     // 大端序
         strVal = QString("模拟量个数:%1 数值依次为:").arg(nlen/2);
        while ( !dataStream.atEnd() ) {
                quint16 number;
                dataStream >> number;
                strVal = strVal+QString("%1,").arg(number);
            }
         ui->textBrowser->append(strVal);
    }
    else  if(nfun==1)//开关量
    {
          strVal = QString("开关量字节个数:%1 开关状态依次为:").arg(nlen);
         for(int i =0;i<vals.size();i++)
          {
                 quint16 number= (quint16) vals.at(i) ;
                 for(int j=0;j<16;j++)
                 {
                             if(GETBYTE(number,j))
                             {
                                 strVal = strVal+" 1,";
                             }
                             else
                             {
                                 strVal = strVal+" 0,";
                             }
                 }
          }
           ui->textBrowser->append(strVal);
    }
   qDebug()<<" strVal:"<<strVal;
}
